package com.community.consumer.controller;

import com.community.common.entity.Order;
import com.community.common.result.Result;
import com.community.consumer.entity.vo.TipResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/message")
@ServerEndpoint("/webSocket/{username}")
@Log4j2
public class TipCpontroller {

    @Autowired
    ConsumerController consumerController;

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static AtomicInteger onlineNum = new AtomicInteger();

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
     */
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();


    @PostMapping("/tryLock")
    public Result tryLock(@RequestBody Order order){
        System.out.println("9999");
        for (int i = 0; i < 600; i++) {
            CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(()->{
                order.setId(1);
                consumerController.joinGroupOverPay(order);
                return null;
            });
            CompletableFuture<String> completableFutureS = CompletableFuture.supplyAsync(()->{
                order.setId(2);
                consumerController.joinGroupOverPay(order);

                return null;
            });
            CompletableFuture<String> completableFutureT = CompletableFuture.supplyAsync(()->{
                order.setId(3);
                consumerController.joinGroupOverPay(order);
                return null;
            });
            CompletableFuture<String> completableFutureF = CompletableFuture.supplyAsync(()->{
                order.setId(4);
                consumerController.joinGroupOverPay(order);
                return null;
            });
            CompletableFuture.allOf(completableFuture,completableFutureS,completableFutureT,completableFutureF).join();
        }

        return null;
    }

    /**
     * 建立连接成功调用
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "username") String userName){
        addOnlineCount();
        sessionPools.put(userName, session);
    }

    /**
     * 发送消息
     * @param tipResult
     */
    @PostMapping("/sendMessage")
    public void sendMessage(@RequestBody TipResult tipResult){
        String userName = "User:"+tipResult.getUserId();
        Session session = sessionPools.get(userName);
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            sendMessage(session,tipResult.getTip());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 发送消息
     */
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }
    /**
     * 给指定用户发送信息
     */
    public void sendInfo(String userName, String message){
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接时调用
     */
    @OnClose
    public void onClose(@PathParam(value = "username") String userName){
        sessionPools.remove(userName);
        subOnlineCount();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

    public static AtomicInteger getOnlineNumber() {
        return onlineNum;
    }

    public static ConcurrentHashMap<String, Session> getSessionPools() {
        return sessionPools;
    }



}
